import cv2
from pyzbar.pyzbar import decode
import os, glob
import pandas as pd
import numpy as np


class QrLoc:
    
    def qr_loc(self, img):
        image = cv2.imread(img)
        detectedBarcodes = decode(image)
        if len(detectedBarcodes) == 0:
            return None
        for barcode in detectedBarcodes:
            qr = barcode.data.decode()
            p = barcode.polygon
            (h, w) = image.shape[:2]
            ps = [p[0], p[1], p[2], p[3]]
            xs = [p[0].x, p[1].x, p[2].x, p[3].x]
            ys = [p[0].y, p[1].y, p[2].y, p[3].y]
            mid_x = sum(xs) / len(xs)
            mid_y = sum(ys) / len(ys)
            p1 = [p for p in ps if (p.x < mid_x and p.y < mid_y)][0]
            p2 = [p for p in ps if (p.x > mid_x and p.y < mid_y)][0]
            p3 = [p for p in ps if (p.x > mid_x and p.y > mid_y)][0]
            p4 = [p for p in ps if (p.x < mid_x and p.y > mid_y)][0]
            
            # p1 p2    (0,0)---->x
            # p3 p4        |  y
            #            \|/
            # self._show(image, [p2])
            dic = dict(
                text=qr,
                p1=[p1.x, p1.y],
                p2=[p2.x, p2.y],
                p3=[p3.x, p3.y],
                p4=[p4.x, p4.y],
                h=h,
                w=w,
            )
            return dic
        return None
    
    def _show(self, image, ps):
        for p in ps:
            cv2.circle(image, p, 10, (0, 0, 255), 10)
        image = cv2.resize(image, (800, 600))
        cv2.imshow("Image", image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    
    def get_all(self):
        images = glob.glob('../desktop_experiment/img/*.JPG')
        dic = {}
        for fname in images:
            data = self.qr_loc(fname)
            if data:
                dic[fname] = data
        return dic


if __name__ == '__main__':
    q = QrLoc()
